import {Base64} from 'js-base64'

function to_b64(str:string){
    return encodeURIComponent(Base64.encode(str))
}

interface DirItem{
    name:string
    path:string
    sub_dirs:string[]
    videos:string[]
    error?:string
}


export class Repo{
    sub_repos:Repo[]=[]
    parent:Repo|null=null
    constructor(public name:string,public path:string,public sub_dir_names:string[], public videos:string[],public error:string=''){}

    async get_sub_repo(dir_name:string){
        for (const repo of this.sub_repos) {
            if (repo.name==dir_name) {
                return repo
            }
        }
        const repo= await this._fetch_sub_repo(dir_name)
        repo.parent=this
        this.sub_repos.push(repo)
        return repo

    }

    static InvalidRepo(error:string){
        return new Repo('Invalid','Invalid',[],[],error)
    }

    static fromItem(item:DirItem){
        return new Repo(item.name,encodeURIComponent(item.path),item.sub_dirs,item.videos,item.error)
    }

    async _fetch_sub_repo(dir_name){
        const api=`/api/video/repo?pid=${this.path}&did=${to_b64(dir_name)}`
        console.log('Fetch repo:',dir_name,to_b64(dir_name))
        const res= await fetch(api)
        if (res.ok==false){
            console.error('Fetch sub dir error:',this.name,dir_name)
            return Repo.InvalidRepo('HTTP Error:'+res.statusText)
        }
        const item=(await res.json()) as DirItem
        return Repo.fromItem(item)
    }
    
    static async fetch_root_repo(refresh=false){
        let api='/api/video/root'
        // if (refresh) {
        //     api+='?refresh=true'
        // }
        const res= await fetch(api)
        if (res.ok==false) {
            console.error('Get video root dir items failed!')
            return Repo.InvalidRepo('HTTP Error:'+res.statusText)
        }
        const items= (await res.json()) as DirItem[]
        console.log('Get root dir item count:',items.length)
        const sub_dir_names=items.map(item=>item.name)
        const root_repo= new Repo('Root','',sub_dir_names,[])
        const sub_dirs=items.map(item=>{
            const sub_dir= Repo.fromItem(item)
            sub_dir.parent=root_repo
            return sub_dir
        })
        root_repo.sub_repos=sub_dirs
        return root_repo
    }
    make_video_url(video_name){
        const encoded_name=to_b64(video_name)
        const url='/api/video/stream'+`?pid=${this.path}&vid=${encoded_name}`
        // console.log('Make video url:',video_name,encoded_name)
        // const res= await fetch(api)
        // if (!res.ok){
        //     console.log('Fetch video url failed:',res.statusText)
        //     return ''
        // }
        return url
    }
}
